<template>
  <div class="order-supplement-page">
    <nut-form ref="formRef" :model-value="formData" :rules="rules">
      <!-- 客户信息 -->
      <nut-cell-group title="客户信息">
        <nut-form-item label="客户姓名" required prop="customName" :rules="[{ required: true, message: '请输入客户姓名' }]">
          <nut-input v-model="formData.customName" placeholder="请输入客户姓名" clearable />
        </nut-form-item>

        <nut-form-item label="客户手机号" required prop="customPhone" :rules="phoneRules">
          <nut-input v-model="formData.customPhone" placeholder="请输入客户手机号" type="tel" clearable />
        </nut-form-item>

        <nut-form-item label="证件类型" prop="idType">
          <nut-radio-group v-model="formData.idType" direction="horizontal">
            <nut-radio label="00">身份证</nut-radio>
            <nut-radio label="01">驾驶证</nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="证件号" required prop="customIdCard" :rules="[{ required: true, message: '请输入证件号' }]">
          <nut-input v-model="formData.customIdCard" placeholder="请输入证件号" clearable />
        </nut-form-item>

        <nut-form-item label="客户邮箱" prop="customEmail">
          <nut-input v-model="formData.customEmail" placeholder="请输入客户邮箱" type="email" clearable />
        </nut-form-item>
      </nut-cell-group>

      <!-- 车辆信息 -->
      <nut-cell-group title="车辆信息">
        <nut-form-item label="车架号" required prop="vinCode" :rules="[{ required: true, message: '请输入车架号' }]">
          <div class="vin-input">
            <nut-input v-model="formData.vinCode" placeholder="请输入车架号" clearable />
            <nut-button size="small" type="primary" @click="handleVehicleOcr"> 行驶证识别 </nut-button>
          </div>
        </nut-form-item>

        <nut-form-item label="发动机号" required prop="engineNumber" :rules="[{ required: true, message: '请输入发动机号' }]">
          <nut-input v-model="formData.engineNumber" placeholder="请输入发动机号" clearable />
        </nut-form-item>

        <nut-form-item label="车牌号" prop="licensePlateNumber">
          <nut-input v-model="formData.licensePlateNumber" placeholder="请输入车牌号" clearable />
        </nut-form-item>

        <nut-form-item label="车辆类型" required prop="vehicleType" :rules="[{ required: true, message: '请输入车辆类型' }]">
          <nut-input v-model="formData.vehicleType" placeholder="请输入车辆类型" clearable />
        </nut-form-item>

        <nut-form-item label="品牌型号" required prop="model" :rules="[{ required: true, message: '请输入品牌型号' }]">
          <nut-input v-model="formData.model" placeholder="请输入品牌型号" clearable />
        </nut-form-item>

        <nut-form-item label="使用性质" required prop="useNature" :rules="[{ required: true, message: '请输入使用性质' }]">
          <nut-input v-model="formData.useNature" placeholder="请输入使用性质" clearable />
        </nut-form-item>

        <nut-form-item label="核载人数" prop="passengerCapacity">
          <nut-input v-model="formData.passengerCapacity" placeholder="请输入核载人数" type="number" clearable />
        </nut-form-item>

        <nut-form-item label="新车发票价" required prop="carPrice" :rules="amountRules">
          <nut-input v-model="formData.carPrice" placeholder="请输入新车发票价" type="number" clearable />
        </nut-form-item>

        <nut-form-item label="购车发票日期" required prop="payCarTime" :rules="[{ required: true, message: '请选择购车发票日期' }]">
          <nut-input
            v-model="formData.payCarTime"
            placeholder="请选择购车发票日期"
            readonly
            @click="openPayCarTimePicker"
          />
        </nut-form-item>

        <nut-form-item label="其他信息" prop="otherMessage">
          <nut-textarea v-model="formData.otherMessage" placeholder="请输入其他信息" :rows="3" />
        </nut-form-item>
      </nut-cell-group>

      <!-- 保险信息 -->
      <nut-cell-group :title="'保险信息'">
        <nut-form-item label="商业保险单号" prop="insuranceNo">
          <nut-input v-model="formData.insuranceNo" placeholder="请输入商业保险单号" clearable />
        </nut-form-item>

        <nut-form-item label="商业保险公司" prop="insuranceCompany">
          <nut-input v-model="formData.insuranceCompany" placeholder="请输入商业保险公司" clearable />
        </nut-form-item>

        <nut-form-item label="商业保险开始时间" prop="insuranceStartTime">
          <nut-input
            v-model="formData.insuranceStartTime"
            placeholder="请选择商业保险开始时间"
            readonly
            @click="openInsuranceStartPicker"
          />
        </nut-form-item>

        <nut-form-item label="商业保险结束时间" prop="insuranceEndTime">
          <nut-input
            v-model="formData.insuranceEndTime"
            placeholder="请选择商业保险结束时间"
            readonly
            @click="openInsuranceEndPicker"
          />
        </nut-form-item>
      </nut-cell-group>

      <!-- 附件上传 -->
      <nut-cell-group title="附件">
        <div class="file-upload-section">
          <div v-for="(file, index) in fileList" :key="index" class="file-item">
            <div class="file-info">
              <span class="file-name">{{ file.name || `附件 ${index + 1}` }}</span>
              <nut-button size="small" type="danger" @click="removeFile(index)">删除</nut-button>
            </div>
            <img v-if="file.url" :src="file.url" alt="附件预览" class="file-preview" />
          </div>
          <nut-button type="primary" block @click="handleFileUpload">上传图片</nut-button>
          <input ref="fileInputRef" type="file" accept="image/*" multiple style="display: none" @change="handleFileChange" />
        </div>
      </nut-cell-group>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <nut-button type="default" block :loading="tempStorageLoading" @click="handleTempStorage">暂存</nut-button>
        <nut-button type="default" block @click="handleCancel">取消</nut-button>
        <nut-button type="primary" block :loading="submitting" @click="handleSubmit">提交</nut-button>
      </div>
    </nut-form>

    <!-- 行驶证识别弹窗 -->
    <nut-popup v-model:visible="showVehicleOcrModal" position="center" round :style="{ padding: '24px', width: '90%' }">
      <div class="vehicle-ocr-modal">
        <h3 class="modal-title">行驶证识别</h3>
        <div class="ocr-upload">
          <input
            ref="vehicleOcrFileInputRef"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleVehicleOcrFileChange"
          />
          <nut-button type="primary" block @click="triggerVehicleOcrFileInput">上传行驶证照片</nut-button>
          <div v-if="vehicleOcrImageUrl" class="ocr-preview">
            <img :src="vehicleOcrImageUrl" alt="行驶证预览" />
          </div>
        </div>
        <div class="modal-actions">
          <nut-button plain type="default" @click="showVehicleOcrModal = false">取消</nut-button>
          <nut-button type="primary" :loading="vehicleOcrLoading" @click="confirmVehicleOcr">识别</nut-button>
        </div>
      </div>
    </nut-popup>

    <!-- 购车发票日期选择 -->
    <nut-popup v-model:visible="payCarTimePickerVisible" position="bottom">
      <nut-date-picker
        v-model="payCarTimePickerValue"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        :three-dimensional="false"
        @confirm="onPayCarTimeConfirm"
        @cancel="payCarTimePickerVisible = false"
      />
    </nut-popup>

    <!-- 商业保险开始时间选择 -->
    <nut-popup v-model:visible="insuranceStartPickerVisible" position="bottom">
      <nut-date-picker
        v-model="insuranceStartPickerValue"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        :three-dimensional="false"
        @confirm="onInsuranceStartConfirm"
        @cancel="insuranceStartPickerVisible = false"
      />
    </nut-popup>

    <!-- 商业保险结束时间选择 -->
    <nut-popup v-model:visible="insuranceEndPickerVisible" position="bottom">
      <nut-date-picker
        v-model="insuranceEndPickerValue"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        :three-dimensional="false"
        @confirm="onInsuranceEndConfirm"
        @cancel="insuranceEndPickerVisible = false"
      />
    </nut-popup>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showDialog } from '@nutui/nutui';
  import {
    fetchOrderDetail,
    tempStorageOrderSupplement,
    submitOrderSupplement,
    vehicleLicenseOcr,
    type OrderDetail,
    type OrderSupplementPayload,
  } from '@/api/order';
  import { uploadFile } from '@/api';

  const router = useRouter();
  const route = useRoute();

  const formRef = ref<any>(null);
  const submitting = ref(false);
  const tempStorageLoading = ref(false);
  const fileInputRef = ref<HTMLInputElement | null>(null);

  // 行驶证识别
  const showVehicleOcrModal = ref(false);
  const vehicleOcrFileInputRef = ref<HTMLInputElement | null>(null);
  const vehicleOcrImageUrl = ref('');
  const vehicleOcrLoading = ref(false);

  // 日期选择相关（组件使用 Date 对象，接口仍用 yyyy-MM-dd 字符串）
  const minDate = new Date(2000, 0, 1);
  const maxDate = new Date(2100, 11, 31);

  const payCarTimePickerVisible = ref(false);
  const payCarTimePickerValue = ref<Date | null>(null);

  const insuranceStartPickerVisible = ref(false);
  const insuranceStartPickerValue = ref<Date | null>(null);

  const insuranceEndPickerVisible = ref(false);
  const insuranceEndPickerValue = ref<Date | null>(null);

  const formatDate = (date: Date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };

  const todayStr = formatDate(new Date());

  // 订单ID
  const orderId = ref('');

  // 表单数据
  const formData = reactive<OrderSupplementPayload>({
    orderId: '',
    idType: '00',
    customName: '',
    customIdCard: '',
    customPhone: '',
    customEmail: '',
    fileList: [],
    vinCode: '',
    engineNumber: '',
    licensePlateNumber: '',
    vehicleType: '',
    model: '',
    useNature: '',
    passengerCapacity: '',
    carPrice: 0,
    payCarTime: todayStr,
    otherMessage: '',
    insuranceNo: '',
    insuranceStartTime: todayStr,
    insuranceEndTime: todayStr,
    insuranceCompany: '',
  });

  // 文件列表
  const fileList = ref<Array<{ url: string; name?: string }>>([]);

  // 表单验证规则
  const phoneRules = [
    { required: true, message: '请输入客户手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
  ];

  const amountRules = [{ required: true, message: '请输入金额' }, { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额' }];

  const rules = {
    customName: [{ required: true, message: '请输入客户姓名' }],
    customPhone: phoneRules,
    customIdCard: [{ required: true, message: '请输入证件号' }],
    vinCode: [{ required: true, message: '请输入车架号' }],
    engineNumber: [{ required: true, message: '请输入发动机号' }],
    vehicleType: [{ required: true, message: '请输入车辆类型' }],
    model: [{ required: true, message: '请输入品牌型号' }],
    useNature: [{ required: true, message: '请输入使用性质' }],
    carPrice: amountRules,
    payCarTime: [{ required: true, message: '请选择购车发票日期' }],
  };

  const isInsuranceDateOrderValid = () => {
    if (!formData.insuranceStartTime || !formData.insuranceEndTime) return true;
    const start = new Date(formData.insuranceStartTime);
    const end = new Date(formData.insuranceEndTime);
    return start.getTime() <= end.getTime();
  };

  const normalizeDate = (value?: string) => {
    if (!value) return '';
    // 只保留前 10 位，确保格式为 yyyy-MM-dd
    return value.slice(0, 10);
  };

  // 加载订单详情（用于回填数据）
  const loadOrderDetail = async () => {
    const id = route.query.orderId as string;
    if (!id) {
      showToast.text('订单ID不能为空');
      router.back();
      return;
    }

    orderId.value = id;
    formData.orderId = id;

    try {
      const { code, data, msg }: any = await fetchOrderDetail(id);
      if (code !== 200) {
        showToast.text(msg || '获取订单详情失败');
        return;
      }
      const detail = data as OrderDetail;
      if (detail) {
        // 回填已有数据
        formData.customName = detail.customName || '';
        formData.customPhone = detail.customPhone || '';
        formData.customIdCard = detail.customIdCard || '';
        formData.customEmail = detail.customEmail || '';
        formData.idType = detail.idType || '00';
        formData.vinCode = detail.vinCode || '';
        formData.engineNumber = detail.engineNumber || '';
        formData.licensePlateNumber = detail.licensePlateNumber || '';
        formData.vehicleType = detail.vehicleType || '';
        formData.model = detail.model || '';
        formData.useNature = detail.useNature || '';
        formData.passengerCapacity = detail.passengerCapacity || '';
        formData.carPrice = detail.carPrice || 0;
        // 日期字段：如果后端无值，则保留原本的默认当天
        formData.payCarTime = detail.payCarTime || formData.payCarTime;
        formData.otherMessage = detail.otherMessage || '';
        formData.insuranceNo = detail.insuranceNo || '';
        formData.insuranceStartTime = detail.insuranceStartTime || formData.insuranceStartTime;
        formData.insuranceEndTime = detail.insuranceEndTime || formData.insuranceEndTime;
        formData.insuranceCompany = detail.insuranceCompany || '';

        // 回填附件
        if (detail.fileList && detail.fileList.length > 0) {
          fileList.value = detail.fileList.map((url) => ({ url }));
          formData.fileList = detail.fileList;
        }
      }
    } catch (error: any) {
      console.error('获取订单详情失败', error);
    }
  };

  // 文件上传
  const handleFileUpload = () => {
    fileInputRef.value?.click();
  };

  const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const files = target.files;
    if (!files || files.length === 0) return;

    for (const file of Array.from(files)) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        showToast.text('请选择图片文件');
        continue;
      }

      // 验证文件大小（限制 5MB）
      if (file.size > 5 * 1024 * 1024) {
        showToast.text('图片大小不能超过 5MB');
        continue;
      }

      try {
        const result = await uploadFile(file);
        if (result?.url) {
          fileList.value.push({ url: result.url, name: file.name });
          formData.fileList = fileList.value.map((item) => item.url);
        } else {
          showToast.text('图片上传失败');
        }
      } catch (error: any) {
        console.error('图片上传失败', error);
        showToast.text(error?.message || '图片上传失败');
      }
    }

    // 清空 input，以便可以重复选择同一文件
    if (target) {
      target.value = '';
    }
  };

  const removeFile = (index: number) => {
    fileList.value.splice(index, 1);
    formData.fileList = fileList.value.map((item) => item.url);
  };

  // 行驶证识别相关
  const handleVehicleOcr = () => {
    showVehicleOcrModal.value = true;
    vehicleOcrImageUrl.value = '';
  };

  const triggerVehicleOcrFileInput = () => {
    vehicleOcrFileInputRef.value?.click();
  };

  const handleVehicleOcrFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      showToast.text('请选择图片文件');
      return;
    }

    // 验证文件大小（限制 5MB）
    if (file.size > 5 * 1024 * 1024) {
      showToast.text('图片大小不能超过 5MB');
      return;
    }

    try {
      const result = await uploadFile(file);
      if (result?.url) {
        vehicleOcrImageUrl.value = result.url;
      } else {
        showToast.text('图片上传失败');
      }
    } catch (error: any) {
      console.error('图片上传失败', error);
      showToast.text(error?.message || '图片上传失败');
    } finally {
      if (target) {
        target.value = '';
      }
    }
  };

  const confirmVehicleOcr = async () => {
    if (!vehicleOcrImageUrl.value) {
      showToast.text('请先上传行驶证图片');
      return;
    }

    try {
      vehicleOcrLoading.value = true;
      const result = await vehicleLicenseOcr(vehicleOcrImageUrl.value);
      if (result) {
        formData.vinCode = result.vinCode || formData.vinCode;
        formData.engineNumber = result.engineNumber || formData.engineNumber;
        formData.licensePlateNumber = result.licensePlateNumber || formData.licensePlateNumber;
        formData.vehicleType = result.vehicleType || formData.vehicleType;
        formData.model = result.model || formData.model;
        formData.useNature = result.useNature || formData.useNature;
        formData.passengerCapacity = result.passengerCapacity || formData.passengerCapacity;
      }
      showToast.text('识别成功');
      showVehicleOcrModal.value = false;
      vehicleOcrImageUrl.value = '';
    } catch (error: any) {
      console.error('行驶证识别失败', error);
      showToast.text(error?.message || '行驶证识别失败');
    } finally {
      vehicleOcrLoading.value = false;
    }
  };

  // 日期选择相关方法
  const openPayCarTimePicker = () => {
    payCarTimePickerValue.value = formData.payCarTime ? new Date(formData.payCarTime) : new Date();
    payCarTimePickerVisible.value = true;
  };

  const onPayCarTimeConfirm = () => {
    if (payCarTimePickerValue.value) {
      formData.payCarTime = formatDate(payCarTimePickerValue.value);
    }
    payCarTimePickerVisible.value = false;
  };

  const openInsuranceStartPicker = () => {
    insuranceStartPickerValue.value = formData.insuranceStartTime ? new Date(formData.insuranceStartTime) : new Date();
    insuranceStartPickerVisible.value = true;
  };

  const onInsuranceStartConfirm = () => {
    if (insuranceStartPickerValue.value) {
      formData.insuranceStartTime = formatDate(insuranceStartPickerValue.value);
    }
    insuranceStartPickerVisible.value = false;
  };

  const openInsuranceEndPicker = () => {
    insuranceEndPickerValue.value = formData.insuranceEndTime ? new Date(formData.insuranceEndTime) : new Date();
    insuranceEndPickerVisible.value = true;
  };

  const onInsuranceEndConfirm = () => {
    if (insuranceEndPickerValue.value) {
      formData.insuranceEndTime = formatDate(insuranceEndPickerValue.value);
    }
    insuranceEndPickerVisible.value = false;
  };

  // 暂存
  const handleTempStorage = async () => {
    formRef.value?.validate().then(async ({ valid, errors }: any) => {
      if (!valid) {
        console.warn(errors);
        return;
      }

      if (!isInsuranceDateOrderValid()) {
        showToast.text('商业保险开始时间不能晚于结束时间');
        return;
      }

      try {
        tempStorageLoading.value = true;

        const payload: OrderSupplementPayload = {
          ...formData,
          carPrice: Number(formData.carPrice),
          payCarTime: normalizeDate(formData.payCarTime),
          insuranceStartTime: normalizeDate(formData.insuranceStartTime),
          insuranceEndTime: normalizeDate(formData.insuranceEndTime),
        };

        await tempStorageOrderSupplement(payload);
        showToast.text('暂存成功');
      } catch (error: any) {
        console.error('暂存失败', error);
        showToast.text(error?.message || '暂存失败');
      } finally {
        tempStorageLoading.value = false;
      }
    });
  };

  // 提交
  const handleSubmit = async () => {
    formRef.value?.validate().then(async ({ valid, errors }: any) => {
      if (!valid) {
        console.warn(errors);
        return;
      }

       if (!isInsuranceDateOrderValid()) {
         showToast.text('商业保险开始时间不能晚于结束时间');
         return;
       }

      try {
        submitting.value = true;

        const payload: OrderSupplementPayload = {
          ...formData,
          carPrice: Number(formData.carPrice),
          payCarTime: normalizeDate(formData.payCarTime),
          insuranceStartTime: normalizeDate(formData.insuranceStartTime),
          insuranceEndTime: normalizeDate(formData.insuranceEndTime),
        };

        await submitOrderSupplement(payload);
        showToast.text('提交成功');
        router.back();
      } catch (error: any) {
        console.error('提交失败', error);
        showToast.text(error?.message || '提交失败');
      } finally {
        submitting.value = false;
      }
    });
  };

  // 取消补录
  const handleCancel = () => {
    showDialog({
      title: '提示',
      content: '确定要取消本次补录吗？',
      onOk: () => {
        router.back();
      },
    });
  };

  // 初始化
  onMounted(() => {
    loadOrderDetail();
  });
</script>

<style lang="scss" scoped>
  .order-supplement-page {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 20px;
  }

  .vin-input {
    display: flex;
    align-items: center;
    gap: 10px;

    .nut-input {
      flex: 1;
    }
  }

  .file-upload-section {
    padding: 20px;

    .file-item {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #fff;
      border-radius: 8px;

      .file-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .file-name {
          font-size: 28px;
          color: #333;
        }
      }

      .file-preview {
        width: 100%;
        max-height: 400px;
        border-radius: 8px;
        object-fit: contain;
      }
    }
  }

  .action-buttons {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-top: 20px;
  }

  .vehicle-ocr-modal {
    .modal-title {
      margin: 0 0 20px;
      font-size: 32px;
      text-align: center;
    }

    .ocr-upload {
      margin-bottom: 20px;

      .ocr-preview {
        margin-top: 20px;
        text-align: center;

        img {
          max-width: 100%;
          max-height: 400px;
          border-radius: 8px;
        }
      }
    }

    .modal-actions {
      display: flex;
      justify-content: space-between;
      gap: 20px;

      .nut-button {
        flex: 1;
      }
    }
  }
</style>

